﻿using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient; // Change this using directive
using System.Reflection;
using System.Data;
using MySqlConnector;
using System.IO;

namespace AutoTool
{
    public class Program
    {
        static void Main(string[] args)
        {
           
            const string connectionString = "Data Source=49.65.97.75;Database=news;User ID=root;Password=Ww623025.;pooling=true;port=3306;sslmode=none;CharSet=utf8;";

            Console.WriteLine("输入你要生成代码的表！");
            var tableName = Console.ReadLine();
            Console.WriteLine(@$"正在查询{tableName}表字段......");
            var Columns = GetTableColumns(tableName.Trim(), connectionString);
            if (Columns.Count == 0)
            {
                Console.WriteLine("当前的表名有误或数据库没有创建当前表！");
            }
            var PrimaryKey = GetPrimaryKey(tableName.Trim(), connectionString);

           var dic= GetTableColumnsWithTypes(tableName,connectionString);
            Console.WriteLine(@$"正在生成实体......");
            EntityGenerator.GenerateEntityClass(tableName, dic);
            Console.WriteLine(@$"正在生成输入输出Dto......");
            DtoGenerator.GenerateDtoClass(tableName, dic, "InputDto");
            DtoGenerator.GenerateDtoClass(tableName, dic, "OutDto");
            Console.WriteLine(@$"正在生成仓储......");
            RepositoryGenerator.GenerateRepository(tableName.Trim(), Columns, PrimaryKey);
            Console.WriteLine("生成成功！");
            Console.ReadKey();
        }
        /// <summary>
        /// 查询表的列名
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static List<string>  GetTableColumns(string tableName, string connectionString)
        {
            var columns = new List<string>();
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                var query = $"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{tableName}'";
                using (var command = new MySqlCommand(query, connection))
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        columns.Add(reader["COLUMN_NAME"].ToString());
                    }
                }
            }
            return columns;
        }

        /// <summary>
        /// 查询表的列名和字段类型
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <returns>包含列名和字段类型的字典</returns>
        public static Dictionary<string, string> GetTableColumnsWithTypes(string tableName, string connectionString)
        {
            var columns = new Dictionary<string, string>();
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                var query = $@"
            SELECT COLUMN_NAME, DATA_TYPE
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME = '{tableName}'";

                using (var command = new MySqlCommand(query, connection))
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var columnName = reader["COLUMN_NAME"].ToString();
                        var dataType = reader["DATA_TYPE"].ToString();
                        columns.Add(columnName, dataType);
                    }
                }
            }
            return columns;
        }


        /// <summary>
        /// 查询表的主键
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string GetPrimaryKey(string tableName, string connectionString)
        {
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                string query = $@"
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
            WHERE TABLE_NAME = '{tableName}'
              AND CONSTRAINT_NAME = 'PRIMARY'
              AND TABLE_SCHEMA = DATABASE();";

                using (var command = new MySqlCommand(query, connection))
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        return reader["COLUMN_NAME"].ToString(); // 返回主键列名
                    }
                }
            }

            throw new Exception($"Primary key not found for table {tableName}");
        }

        public void Test(string connectionString) {
            UserStorageRepository userStorageRepository = new UserStorageRepository(connectionString);
            var a = userStorageRepository.GetAllUserStorage();
            //var b = userStorageRepository.GetUserStorageById(Guid.Parse("95cfb80d-140d-6fc5-4685-9c5dae950a05"));
            //        userStorageRepository.InsertUserStorage(new UserStorage()
            //        {
            //            StorageId = Guid.NewGuid(),
            //            UserId = Guid.NewGuid(),
            //            TotalSpace = 100,
            //            UsedSpace = 0,
            //            PlanType = "free",
            //            CreateTime = DateTime.Now,
            //            ExpireTime = DateTime.Now
            //        });

            userStorageRepository.DeleteUserStorage(Guid.Parse("95cfb80d-140d-6fc5-4685-9c5dae950a05"));
        }



    }
}
